﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class lessonUI : MonoBehaviour {

	public LessonInfo lessionInfo = null;
    public LessonInfo lessonTeacher = null;
    public LessonInfo lessonStudent = null;
	
	public GameObject video = null;

	public GameObject game = null;
	public GameObject game1 = null;
	public GameObject game2 = null;

	public GameObject lessonList = null;
	public GameObject about = null;
	public GameObject li = null;

	public lessonElement le1 = null;
	public lessonElement le2 = null;
	public lessonElement le3 = null;
	public lessonElement le4 = null;


	public Button btnDownload1 = null;
	public Button btnDownload2 = null;
	public Button btnDownload3 = null;
	public Button btnDownload4 = null;

    public AudioSource bgMusic = null;
    public GameObject btnBgmusicOff = null;

    public GameObject btnBackToUser = null;
    public GameObject btnUserInfo = null;




	protected int nowIdx = 1;


	public Dictionary<string, LessonCfgData.LessonCfg> data = null;

	private static lessonUI instance = null;
	public static lessonUI GetInstance()
	{
		return instance;
	}

	void Awake()
	{
		instance = this;

	}

	// Use this for initialization
	void Start () {

		gameObject.SetActive (true);
		lessionInfo.gameObject.SetActive (true);

		lessonList.SetActive (false);
		video.SetActive (false);
		game.SetActive (false);

        ShowAbout(false);
        User.GetInstance().Hide();
        UserInfo.GetInstance().Hide();

        yiguzuoqi.GetInstance().Hide();

		downloadProgress.Hide ();





//		ShowLessonList();
    }
	
	// Update is called once per frame
	void Update () {
		
	}

	private List<string> GetUndownloadRes(string typ, string id)
	{
		List<string> li = new List<string> ();
		if ("video" == typ) {
		
			VideoCfgData.VideoCfg cfg = DataManager.videoCfgData.GetCfg (id);
			if (cfg == null)
				return li;
			
			if (ResLoader.HaveDownload (cfg.urlVideo1) == false)
				li.Add (cfg.urlVideo1);
			if (ResLoader.HaveDownload (cfg.urlAudio1) == false)
				li.Add (cfg.urlAudio1);

			if (cfg.VideoType == "multi") {
			
				if (ResLoader.HaveDownload (cfg.urlVideo2) == false)
					li.Add (cfg.urlVideo2);
				if (ResLoader.HaveDownload (cfg.urlAudio2) == false)
					li.Add (cfg.urlAudio2);
				if (ResLoader.HaveDownload (cfg.urlImage) == false)
					li.Add (cfg.urlImage);
			}
		} else if ("game" == typ) {

			GameCfgData.GameCfg cfg = DataManager.gameCfgData.GetCfg (id);
			if (cfg == null)
				return li;

			if (ResLoader.HaveDownload (cfg.mansu.urlMusic) == false)
				li.Add (cfg.mansu.urlMusic);

            if (ResLoader.HaveDownload(cfg.kuaisu.urlMusic) == false)
                li.Add(cfg.kuaisu.urlMusic);

            if (ResLoader.HaveDownload (cfg.urlVideo) == false)
				li.Add (cfg.urlVideo);


		}
        else if ( "yiguzuoqi" == typ )
        {
            YiguzuoqiCfgData.YiguzuoqiCfg cfg = DataManager.yiguzuoqiCfgData.GetCfg(id);
            if (cfg == null)
                return li;

            if (ResLoader.HaveDownload(cfg.urlMansu) == false)
                li.Add(cfg.urlMansu);
            if (ResLoader.HaveDownload(cfg.urlZhongsu) == false)
                li.Add(cfg.urlZhongsu);
            if (ResLoader.HaveDownload(cfg.urlKuaisu) == false)
                li.Add(cfg.urlKuaisu);
            if (ResLoader.HaveDownload(cfg.urlYanzousudu) == false)
                li.Add(cfg.urlYanzousudu);
        }

		return li;
	}
		

	public List<string> GetUndownloadResByLesson( int idx)
	{
		return GetUndownloadResByLesson (idx.ToString ());
	}


	public static bool isLessonDownloading = false;
	public List<string> GetUndownloadResByLesson( string lessonID)
	{
		Dictionary<string, LessonCfgData.LessonCfg> l = DataManager.lessonCfgData.GetLesson(lessonID);
		List<string> res = new List<string> ();
		List<string> l1 = GetUndownloadRes (l ["tingkan"].lessonType, l ["tingkan"].id);
		if (l1.Count > 0) {
			res.AddRange (l1);
		}
		List<string> l2 = GetUndownloadRes (l ["wannao"].lessonType, l ["wannao"].id);
		if (l2.Count > 0) {
			res.AddRange (l2);
		}
		List<string> l3 = GetUndownloadRes (l ["niutiao"].lessonType, l ["niutiao"].id);
		if (l3.Count > 0) {
			res.AddRange (l3);
		}
		List<string> l4 = GetUndownloadRes (l ["qiaoda"].lessonType, l ["qiaoda"].id);
		if (l4.Count > 0) {
			res.AddRange (l4);
		}
        List<string> l5 = GetUndownloadRes(l["yiguzuoqi"].lessonType, l["yiguzuoqi"].id);
        if (l5.Count > 0)
        {
            res.AddRange(l5);
        }

        HashSet<string> tm = new HashSet<string>(res);
        res.Clear();
        List<string> lii = new List<string>(tm);

        return lii;
	}
    

	public void ShowLessonList()
	{

		lessonList.SetActive (true);
        HideLessonInfo();

		//1
		Dictionary<string, LessonCfgData.LessonCfg> l1;
        Dictionary<string, LessonCfgData.LessonCfg> l2;
        Dictionary<string, LessonCfgData.LessonCfg> l3;
        Dictionary<string, LessonCfgData.LessonCfg> l4;

        downloadProgress.Hide();

        if ( DataManager.appUserData.IsNull() )
        {
            nowIdx = 1;
            l1 = DataManager.lessonCfgData.GetLessonByIdx(nowIdx);
            l2 = null;
            l3 = null;
            l4 = null;

            btnBackToUser.SetActive(true);
//            btnUserInfo.SetActive(false);
        }
        else
        {
            l1 = DataManager.lessonCfgData.GetLessonByIdx(nowIdx);
            l2 = DataManager.lessonCfgData.GetLessonByIdx(nowIdx + 1);
            l3 = DataManager.lessonCfgData.GetLessonByIdx(nowIdx + 2);
            l4 = DataManager.lessonCfgData.GetLessonByIdx(nowIdx + 3);

            btnBackToUser.SetActive(false);
//            btnUserInfo.SetActive(true);
        }

        int last = nowIdx + 3;

        if (l1 == null) {

			le1.gameObject.SetActive (false);
		}
		else {


			le1.Init(nowIdx.ToString(), l1["cover"].lessonType);

			le1.gameObject.SetActive (true);

			List<string> li = GetUndownloadResByLesson(nowIdx);
			if (li.Count > 0) {

				btnDownload1.gameObject.SetActive (true);

			} else {
				btnDownload1.gameObject.SetActive (false);
			}


		}


		//2
		
		if (l2 == null)
			le2.gameObject.SetActive (false);
		else {
			le2.Init((nowIdx+1).ToString(), l2["cover"].lessonType);
			le2.gameObject.SetActive (true);

			List<string> li = GetUndownloadResByLesson(nowIdx+1);
			if (li.Count > 0) {

				btnDownload2.gameObject.SetActive (true);


			}else {
				btnDownload2.gameObject.SetActive (false);
			}

		}

		//3
		
		if (l3 == null)
			le3.gameObject.SetActive (false);
		else {
			le3.Init((nowIdx+2).ToString(), l3["cover"].lessonType);
			le3.gameObject.SetActive (true);

			List<string> li = GetUndownloadResByLesson(nowIdx+2);
			if (li.Count > 0) {

				btnDownload3.gameObject.SetActive (true);

			}else {
				btnDownload3.gameObject.SetActive (false);
			}
		}

		//4
		
		if (l4 == null)
			le4.gameObject.SetActive (false);
		else {
			le4.Init((nowIdx+3).ToString(), l4["cover"].lessonType);
			le4.gameObject.SetActive (true);

			List<string> li = GetUndownloadResByLesson(nowIdx+3);
			if (li.Count > 0) {

				btnDownload4.gameObject.SetActive (true);

			}else {
				btnDownload4.gameObject.SetActive (false);
			}
		}

		
	}

	public void OnBtnChoose1()
	{
		ShowLessonInfo (nowIdx.ToString ());
	}
	public void OnBtnChoose2()
	{
		ShowLessonInfo ((nowIdx+1).ToString ());
	}
	public void OnBtnChoose3()
	{
		ShowLessonInfo ((nowIdx+2).ToString ());
	}
	public void OnBtnChoose4()
	{
		ShowLessonInfo ((nowIdx+3).ToString ());
	}


	public void OnBtnDownload1()
	{
        if (isLessonDownloading)
            return;
        else
            isLessonDownloading = true;

		List<string> li = GetUndownloadResByLesson(nowIdx);

        ClearCache.AddCacheLesson(nowIdx);

		if (li.Count > 0) {

				int count = 1;
				int total = li.Count;

				foreach (var item in li) {
				
					ResLoader.Load (item, 
						(progress) => {
							//
						downloadProgress.Show(progress, count, total);
					}, 
						(res) => {
							count++;
							if ( count >= total )
							{
								// finish
								// 可以进入
								isLessonDownloading  = false;
								downloadProgress.Hide();

								// 下载按钮消失
								btnDownload1.gameObject.SetActive(false);
							}
					},true, true);
				}

		}
        else
        {
            isLessonDownloading = false;
        }
	}

	public void OnBtnDownload2()
	{
        if (isLessonDownloading)
            return;
        else
            isLessonDownloading = true;

        List<string> li = GetUndownloadResByLesson(nowIdx+1);
        ClearCache.AddCacheLesson(nowIdx+1);
        if (li.Count > 0) {

			int count = 1;
			int total = li.Count;

			downloadProgress.Show(0, count, total);

			isLessonDownloading = true;
			foreach (var item in li) {

				ResLoader.Load (item, 
					(progress) => {
						//
						downloadProgress.Show(progress, count, total);
					}, 
					(res) => {
						count++;
						if ( count >= total )
						{
							// finish
							// 可以进入
							isLessonDownloading  = false;
							downloadProgress.Hide();
						
							// 下载按钮消失
							btnDownload2.gameObject.SetActive(false);
						}
					}, true, true);
			}

		}
        else
        {
            isLessonDownloading = false;
        }
	}

	public void OnBtnDownload3()
	{
        if (isLessonDownloading)
            return;
        else
            isLessonDownloading = true;

        List<string> li = GetUndownloadResByLesson(nowIdx+2);
        ClearCache.AddCacheLesson(nowIdx + 2);
        if (li.Count > 0) {

			int count = 1;
			int total = li.Count;

			downloadProgress.Show(0, count, total);

			isLessonDownloading = true;
			foreach (var item in li) {

				ResLoader.Load (item, 
					(progress) => {
						//
						downloadProgress.Show(progress, count, total);
					}, 
					(res) => {
						count++;
						if ( count >= total )
						{
							// finish
							// 可以进入
							isLessonDownloading  = false;
							downloadProgress.Hide();

							// 下载按钮消失
							btnDownload3.gameObject.SetActive(false);
						}
					}, true, true);
			}

		}
        else
        { isLessonDownloading = false; }
	}

	public void OnBtnDownload4()
	{
        if (isLessonDownloading)
            return;
        else
            isLessonDownloading = true;

        List<string> li = GetUndownloadResByLesson(nowIdx+3);
        ClearCache.AddCacheLesson(nowIdx + 3);
        if (li.Count > 0) {

			int count = 1;
			int total = li.Count;

			downloadProgress.Show(0, count, total);

			isLessonDownloading = true;
			foreach (var item in li) {

				ResLoader.Load (item, 
					(progress) => {
						//
						downloadProgress.Show(progress, count, total);
					}, 
					(res) => {
						count++;
						if ( count >= total )
						{
							// finish
							// 可以进入
							isLessonDownloading  = false;
							downloadProgress.Hide();

							// 下载按钮消失
							btnDownload4.gameObject.SetActive(false);
						}
					}, true, true);
			}

		}
        else
        { isLessonDownloading = false; }
	}

	public void OnBtnLeft()
	{
		nowIdx = nowIdx - 4 ;
		nowIdx = nowIdx > 0 ? nowIdx : 1;

		ShowLessonList ();


	}

	public void OnBtnRight()
	{
		if (nowIdx + 4 > DataManager.lessonCfgData.GetLessonCount ())
			return;

		nowIdx = nowIdx + 4 ;

		ShowLessonList ();


	}

    string nowLessonIdChoosen = "";
	public void ShowLessonInfo(string id)
	{
		gameObject.SetActive (true);
        nowLessonIdChoosen = id;

        if (DataManager.appUserData.IsNull() || DataManager.appUserData.type == "teacher" )
        {
            lessonTeacher.gameObject.SetActive(true);
            lessonStudent.gameObject.SetActive(false);
            
        }
        else
        {
            lessonTeacher.gameObject.SetActive(false);
            lessonStudent.gameObject.SetActive(true);
        }

		lessionInfo.gameObject.SetActive (false);

		data = DataManager.lessonCfgData.GetLesson (id);
		lessonTeacher.Init (id);
        lessonStudent.Init(id);

		lessonList.SetActive (false);
		video.SetActive (false);
		game.SetActive (false);
	}

	public void ShowLessonInfo()
	{

		video.SetActive (false);
		game.SetActive (false);

        lessionInfo.gameObject.SetActive(false);
        if ( DataManager.appUserData.IsNull() )
        {
            
            lessonStudent.gameObject.SetActive(false);
            lessonTeacher.gameObject.SetActive(true);
        }
		else
        {
            if ( DataManager.appUserData.type == "teacher" )
            {
                lessonStudent.gameObject.SetActive(false);
                lessonTeacher.gameObject.SetActive(true);
            }
            else
            {
                lessonStudent.gameObject.SetActive(true);
                lessonTeacher.gameObject.SetActive(false);
            }

        }

		lessonList.SetActive (false);
		gameObject.SetActive (true);



	}

	public void HideLessonInfo()
	{
		lessionInfo.gameObject.SetActive (false);
        lessonStudent.gameObject.SetActive(false);
        lessonTeacher.gameObject.SetActive(false);
	}

	public void OnBtnContent1()
	{
		
		Loading.GetInstance ().StartLoading ();

		StartCoroutine (VideoInit ("tingkan"));

	}

	

	IEnumerator VideoInit(string key)
	{

		yield return new WaitForEndOfFrame ();
		yield return new WaitForEndOfFrame ();
//		yield return new WaitForEndOfFrame ();

		// 视频
		video.SetActive(true);

		gameObject.SetActive (false);

		// 视频
		VideoOperator.GetInstance ().Init (data [key].id, key);

		yield return null;
	}

	public void OnBtnContent2()
	{
		GameCfgData.GameCfg gameCfg = DataManager.gameCfgData.GetCfg (data ["wannao"].id);
		if (gameCfg == null)
			return;

		if (gameCfg.gameType == "0") {
			game.SetActive (true);
			SceneCreator.GetInstance ().Init (data ["wannao"].id, nowLessonIdChoosen);
		} else {
			game.SetActive (true);
			SceneCreator2.GetInstance ().Init (data ["wannao"].id, nowLessonIdChoosen);
		}

		// 游戏
		video.SetActive(false);
		gameObject.SetActive (false);
	}


	public void OnBtnContent3()
	{
		
		Loading.GetInstance ().StartLoading ();

		StartCoroutine (VideoInit ("niutiao"));
	}

	public void OnBtnContent4()
	{
		
		Loading.GetInstance ().StartLoading ();

		StartCoroutine (VideoInit ("qiaoda"));
	}

    public void OnBtnYiguzuoqi()
    {
        gameObject.SetActive(false);

        string id = data["yiguzuoqi"].id;
        yiguzuoqi.GetInstance().Init(id);
    }

	public void OnBtnBack()
	{
//		Application.Quit ();
		ShowLessonList ();
	}

	public void OnBtnAbout()
	{


               ShowAbout(true);
               ShowLi(false);

//        ClearCache.Show();


    }


    public void OnBtnUserinfo()
    {
            UserInfo.GetInstance().Show();
    }

	public void OnBtnBackAbout()
	{
        //		about.SetActive (false);
        //		li.SetActive (true);
        ShowAbout(false);
        ShowLi(true);
	}

    Vector3 bkVector3Li = Vector3.zero;
    public void ShowLi( bool show )
    {
        if (!show)
        {
            bkVector3Li = li.transform.position;
            li.transform.position = new Vector3(10000, 10000, 10000);
        }
        else
        {
            li.transform.position = bkVector3Li;
        }

    }

    Vector3 bkVector3About = Vector3.zero;
    public void ShowAbout(bool show)
    {
        if (!show)
        {
            bkVector3About = about.transform.position;
            about.transform.position = new Vector3(10000, 10000, 10000);
        }
        else
        {
            about.transform.position = bkVector3About;
        }
    }


    public void OnTurnOnBGMusic ()
    {
        bgMusic.Play();
        btnBgmusicOff.SetActive(true);
        bgMusic.playOnAwake = true;
    }

    public void OnTurnOffBGMusic()
    {
        bgMusic.Stop();
        btnBgmusicOff.SetActive(false);
        bgMusic.playOnAwake = false;
    }

    public void OnBtnBackToUser()
    {
        Index.GetInstance().gameObject.SetActive(true);
    }
}
